/**
 * Created by congzhang on 17/11/6.
 */


var http = require("http");
var mime = require("mime");
var url = require("url");
var fs = require("fs");
var formidable = require("formidable");
var path = require("path");
var querystring = require("querystring");
var express = require("express");
var bodyParser = require("body-parser");
var multer = require('multer');
var models = require("./dbs/models.js");


var upload = multer({ dest: './temp' });
var app = express();

app.set("view engine", 'ejs');  // 设置模板引擎
app.set("views", path.join(__dirname, "html"));    // 指定模板目录

app.use(express.static(path.join(__dirname, "statics"))); // 设置静态文件目录
// 将 post 请求的请求体转为对象
app.use(bodyParser.urlencoded({extended: true, uploadDir: "./temp"}));
app.use(bodyParser.json());


function formatDateTime(date) {
    var y = date.getFullYear();
    var m = date.getMonth() + 1;
    m = m < 10 ? ('0' + m) : m;
    var d = date.getDate();
    d = d < 10 ? ('0' + d) : d;
    var h = date.getHours();
    var minute = date.getMinutes();
    minute = minute < 10 ? ('0' + minute) : minute;
    return y + '-' + m + '-' + d+' '+h+':'+minute;
}

app.use(function (req, res, next) {
    res.set('Access-Control-Allow-Origin', "*");

    next()
});

app.get("/", function (req, res) {


    models.Video.find({}).sort({"createDate": -1}).exec(function (err, data) {
        if (err){
            console.log("Error:" + err);
        }else {
            res.render("index", {
                "tbody_data": data,
                "formatDateTime": formatDateTime
            })
        }

    })
});


app.post("/create/", function (req, res) {

    var result_data = {
        "status": true,
        "message": ""
    };

    var name = req.body.name;
    var file_url = req.body.file_url;


    if (!name){
        result_data.status = false;
        result_data.message = "请输入视频的名称";
    }
    else if(!file_url){
        result_data.status = false;
        result_data.message = "请上传视频";
    }

    if (result_data.status){

        var extname = path.extname(file_url);

        var videoType = [".mov", ".mpeg", ".aiff", ".avi", ".mpg", ".qt", ".ram", ".viv", ".mp4", ".MOV"];

        if(videoType.indexOf(extname) == -1){

            result_data.status = false;
            result_data.message = "视频格式不正确, 请重新上传";

        }else{
            var video = new models.Video({
                name : name,
                createDate: new Date(),
                status: 1,
                videoPath : file_url,
                videoImgPath: null
            });

            video.save();

            result_data.status = true;
            result_data.message = "创建成功";

        }

    }

    res.send(result_data);

});


app.post("/uploadVideo/", upload.single('file'), function (req, res) {

    var file_name = req.body.name;    // 文件名称
    var index = req.body.index;       // 第几份

    var file_tmp_path = req.file.path;

    var file_path = path.join("temp", file_name) + "-" + index;
    //  1-1  1-2 1-3

    fs.rename(file_tmp_path, file_path, function (err) {
        if(!err){
            res.send({"status": true});
        }
    })

});



app.post("/mergeVideo/", upload.single('file'), function (req, res) {

    var name = req.body.name;    // 文件名称
    var index = req.body.index;       // 第几份

    var file_name = new Date().getTime().toString() + '_' + name;
    var file_path = path.join("video", file_name);

    for (var i = 0; i < index; i++){
        var old_file_name = path.join("temp", name) + "-" + i;

        var file_data = fs.readFileSync(old_file_name);
        fs.appendFileSync(file_path, file_data);
        fs.unlinkSync(old_file_name)
    }

    var file_url = "/" + file_path;

    name = Date.now();
    var video = new models.Video({
        name : name,
        createDate: new Date(),
        status: 1,
        videoPath : file_url,
        videoImgPath: null
    });

    video.save();

    var result_data = {
        "file_url": file_url,
        "file_name": file_name,
        "status": true,
        "video_id": video._id
    };

    res.send(result_data)

});



app.get("/download/:id", function (req, res) {

    var id = req.params.id;

    models.Video.findById(id, function (err, find_data) {

        var zhuanmaVideoPath =  find_data.zhuanmaVideoPath;

        var download_file_path = "." + zhuanmaVideoPath;
        res.download(download_file_path)
    });

});



app.listen(9101, "0.0.0.0");

